package net.jjjshop.front.controller.lbt;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.jjjshop.common.ali.sms.AliYunSmsUtil;
import net.jjjshop.common.constants.ConfConstants;
import net.jjjshop.common.entity.lbt.JybBusinessOrderEntity;
import net.jjjshop.common.entity.lbt.JybTradeOrderEntity;
import net.jjjshop.common.entity.lbt.LbSysConfigEntity;
import net.jjjshop.common.entity.lbt.LbUserWalletEntity;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.entity.user.UserBill;
import net.jjjshop.common.service.lbt.*;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.BigDecimalUtil;
import net.jjjshop.common.util.OrderUtil;
import net.jjjshop.framework.common.api.ApiResult;
import net.jjjshop.framework.util.LoginUtil;
import net.jjjshop.front.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 交易订单表 控制器
 */
@RestController
@RequestMapping("/front/jybtradeorder")
@Api(tags = "交易订单表")
public class JybTradeOrderController extends BaseController {
    @Autowired
    private JybTradeOrderService jybTradeOrderService;
    @Autowired
    private JybBusinessOrderService jybBusinessOrderService;
    @Autowired
    private LbUserWalletService walletService;
    @Autowired
    private UserBillService userBillService;

    @Autowired
    private UserService userService;
    @Autowired
    private LbSysConfigService sysConfigService;



    /**
     * 列表信息
     */
    @ApiOperation(value = "列表信息")
    @GetMapping("/list")
    public ApiResult<?> list(@RequestParam("tType") Integer tType, @RequestParam("classType") Integer classType, Integer status, Integer page, Integer limit){
        return ApiResult.ok(jybTradeOrderService.getList(null,tType,status,classType,page,limit));
    }



    /**
     * 根据订单号查询订单详情
     */
    @ApiOperation(value = "详情数据")
    @GetMapping("/info/{orderNo}")
    public ApiResult<JybTradeOrderEntity> info(@PathVariable("orderNo") String orderNo){
		JybTradeOrderEntity jybTradeOrder = jybTradeOrderService.queryOrderInfo(orderNo);

        return ApiResult.ok(jybTradeOrder);
    }

    /**
     * 新增数据
     */
    @ApiOperation(value = "新增数据")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public  ApiResult<?> save(@RequestBody @Validated JybTradeOrderEntity jybTradeOrder){

        JybBusinessOrderEntity byId = jybBusinessOrderService.getById(jybTradeOrder.getGid());
        jybTradeOrder.setUid(LoginUtil.getUserId());
        jybTradeOrder.setCreateTime(new Date());
        jybTradeOrder.setAppId(10001);
        jybTradeOrder.setNo(OrderUtil.generateOrderNumber());
        jybTradeOrder.setPrice(byId.getPrice());
        jybTradeOrder.setClassType(byId.getClassType());
        if (null == byId || null ==byId.getId()){
            return ApiResult.fail("没有找到交易信息");
        }
        if (0!=byId.getStatus()){
            return ApiResult.fail("不在交易状态");
        }
        if (byId.getUid() == LoginUtil.getUserId()){
            return ApiResult.fail("自己不能交易");
        }
        if (byId.getNum().doubleValue() < jybTradeOrder.getNum().doubleValue()) {
            return ApiResult.fail("交易数量大于订单数量");
        }
        byId.setNum(BigDecimalUtil.subDouble(byId.getNum(), jybTradeOrder.getNum()));
        synchronized(this){
//添加分红池
            LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
            BigDecimal xDa = new BigDecimal(0.05);//下单百分之5分红池

            if (byId.getType() == 1) {
                jybTradeOrder.setPayId(byId.getPayId());
                //交易商品为出售，当前用户为买家
                //

//            if (byId.getNum() == jybTradeOrder.getNum()){
//                byId.setStatus(1);
//            }

                jybTradeOrder.setSellerId(byId.getUid());
                jybTradeOrder.setBuyerId( LoginUtil.getUserId());

                if (jybBusinessOrderService.updateById(byId)) {

                    if (jybTradeOrderService.save(jybTradeOrder)) {
                        return ApiResult.ok(jybTradeOrder.getNo());
                    } else {
                        throw new RuntimeException("订单异常");
                    }

                }
            }else if (byId.getType() == 2){

                jybTradeOrder.setBuyerId(byId.getUid());
                jybTradeOrder.setSellerId(LoginUtil.getUserId());
                //挂卖处理
                LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(LoginUtil.getUserId());
                if (null == walletInfo || null == walletInfo.getId()) {
                    return ApiResult.fail("没有找到钱包");
                }
                if (null == walletInfo.getScore() || walletInfo.getScore().doubleValue() <= 0) {
                    return ApiResult.fail("没有可交易权益卡");
                }
                BigDecimal sxf = BigDecimalUtil.mul(jybTradeOrder.getNum(), new BigDecimal(ConfConstants.HANG_SALE_FEES));
                if (jybTradeOrder.getClassType() == 0){
                    //出售权益卡
                    BigDecimal total = BigDecimalUtil.addDouble(jybTradeOrder.getNum(),sxf);
                    //扣除手续费百分之比

                    //
                    if (walletInfo.getScore().doubleValue() < total.doubleValue()) {
                        return ApiResult.fail("出售数量不够");
                    }
                    walletInfo.setScore(BigDecimalUtil.subDouble(walletInfo.getScore(), total));
                    lbSysConfigEntity.setDividendPool(BigDecimalUtil.addDouble(sxf,lbSysConfigEntity.getDividendPool()));
                    sysConfigService.save(lbSysConfigEntity);
                    userBillService.addBillRecord("消费分红贡献",ConfConstants.DIVIDEND_POOL,1,sxf,LoginUtil.getUserId(),2);

                    if(! userBillService.addBillRecord("出售权益卡", ConfConstants.INTEGRAL_TYPE,0,total,LoginUtil.getUserId(),null)){
                        throw new RuntimeException("卖出异常");
                    }

                }else if (byId.getClassType() == 1){
                    //出售佣金

                    //
                    if (walletInfo.getMoney().doubleValue() < jybTradeOrder.getNum().doubleValue()) {
                        return ApiResult.fail("出售数量不够");
                    }
                    walletInfo.setMoney(BigDecimalUtil.subDouble(walletInfo.getMoney(),jybTradeOrder.getNum()));
                    //抵扣权益卡
                    walletInfo.setScore(BigDecimalUtil.subDouble(walletInfo.getScore(), sxf));

                    if(! userBillService.addBillRecord("出售贡献值",ConfConstants.COMMISSION_TYPE,0,jybTradeOrder.getNum(),LoginUtil.getUserId(),null)){
                        throw new RuntimeException("出售异常");
                    }
                    if(! userBillService.addBillRecord("出售贡献值抵扣",ConfConstants.INTEGRAL_TYPE,0,sxf,LoginUtil.getUserId(),null)){
                        throw new RuntimeException("出售异常");
                    }
                    lbSysConfigEntity.setDividendPool(BigDecimalUtil.addDouble(sxf,lbSysConfigEntity.getDividendPool()));
                    sysConfigService.save(lbSysConfigEntity);
                    userBillService.addBillRecord("消费分红贡献",ConfConstants.DIVIDEND_POOL,1,sxf,LoginUtil.getUserId(),2);

                }
                if (jybBusinessOrderService.updateById(byId)) {
                    if (walletService.updateById(walletInfo)&&jybTradeOrderService.save(jybTradeOrder)) {
                        return ApiResult.ok(jybTradeOrder.getNo());
                    } else {
                        throw new RuntimeException("卖出异常");
                    }

                }


            }
            return ApiResult.fail();
        }



    }


    /**
     * 修改数据
     */
    @ApiOperation(value = "修改数据")
    @PostMapping("/update")
    public ApiResult<?> update(@RequestBody @Validated JybTradeOrderEntity jybTradeOrder){
        if (jybTradeOrderService.updateById(jybTradeOrder)) {
            return ApiResult.ok();
        }
        return ApiResult.fail();
    }

    /**
     * 已付款通知
     */
    @ApiOperation(value = "已付款通知,传id,voucherImg两个字段")
    @PostMapping("/payNotice")
    public ApiResult<?> payNotice(@RequestParam("no") String no,String image){
        JybTradeOrderEntity byId = jybTradeOrderService.queryOrderInfo(no);
//        if (StringUtils.isEmpty(jybTradeOrder.getVoucherImg())){
//            return ApiResult.fail("支付凭证不能为空");
//        }
        if (null == byId || null ==byId.getId()){
            return ApiResult.fail("没有找到交易订单");
        }
        if (byId.getStatus() != 0){
            return ApiResult.fail("订单不是待支付状态");
        }
        byId.setVoucherImg(image);
        byId.setStatus(1);
//        byId.setVoucherImg(jybTradeOrder.getVoucherImg());
        if (jybTradeOrderService.updateById(byId)) {
            User user = userService.getById(byId.getSellerId());
            AliYunSmsUtil.sendSms(user.getMobile(), 1234L,AliYunSmsUtil.templateCodeNotice);
            return ApiResult.ok();

        }
        return ApiResult.fail();
    }

    /**
     * 交易放币
     */
    @ApiOperation(value = "交易放币")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/transaction")
    public ApiResult<?> transaction(@RequestParam("no") String no){
        JybTradeOrderEntity byId = jybTradeOrderService.queryOrderInfo(no);
        if (null == byId || null ==byId.getId()){
            return ApiResult.fail("没有找到交易订单");
        }
        if (byId.getStatus() != 1){
            return ApiResult.fail("不是已支付状态");
        }
        if (LoginUtil.getUserId().intValue() != byId.getSellerId().intValue()){
            return ApiResult.fail("非卖家不能放币");
        }
        byId.setStatus(2);
        LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(byId.getBuyerId());
        if (null ==walletInfo || null ==walletInfo.getId()){
            return ApiResult.fail("没有找到卖家钱包");
        }

        if (byId.getClassType() == 0){
            walletInfo.setScore(BigDecimalUtil.addDouble(byId.getNum(),walletInfo.getScore()));
            if(! userBillService.addBillRecord("购买权益卡",ConfConstants.INTEGRAL_TYPE,1,byId.getNum(),byId.getBuyerId(),null)){
                throw new RuntimeException("放行异常，联系客服");
            }
            if(! userBillService.addBillRecord("出售权益卡",ConfConstants.INTEGRAL_TYPE,0,byId.getNum(),byId.getSellerId(),null)){
                throw new RuntimeException("放行异常，联系客服");
            }
        }else if (byId.getClassType() == 1){
            walletInfo.setMoney(BigDecimalUtil.addDouble(byId.getNum(),walletInfo.getMoney()));
            if(! userBillService.addBillRecord("购买贡献值",ConfConstants.COMMISSION_TYPE,1,byId.getNum(),byId.getBuyerId(),null)){
                throw new RuntimeException("放行异常，联系客服");
            }
            if(! userBillService.addBillRecord("出售贡献值",ConfConstants.COMMISSION_TYPE,0,byId.getNum(),byId.getSellerId(),null)){
                throw new RuntimeException("放行异常，联系客服");
            }
        }


        if (jybTradeOrderService.updateById(byId)) {
           if ( walletService.updateById(walletInfo)){
               return ApiResult.ok();
           }else{
               throw new RuntimeException("放币异常");
           }

        }
        return ApiResult.fail();
    }


    /**
     * 取消订单
     */
    @ApiOperation(value = "取消订单")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/cancel")
    public ApiResult<String> cancel( @RequestParam("id") Integer id,Integer type){
        JybTradeOrderEntity byId = jybTradeOrderService.getById(id);
        if (null == byId || null ==byId.getId()){
            return ApiResult.fail("没有找到交易订单");
        }


        JybBusinessOrderEntity bean = jybBusinessOrderService.getById(byId.getGid());
        if (null == bean || null ==bean.getId()){
            return ApiResult.fail("没有找到交易信息");
        }
        bean.setNum(BigDecimalUtil.addDouble(bean.getNum(), byId.getNum()));
        bean.setStatus(0);
        byId.setStatus(3);
        if (bean.getType() == 2){
            Integer uid = byId.getSellerId();
            //如果回收，需要处理退币
            //挂卖处理
            LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(uid);
            if (null == walletInfo || null == walletInfo.getId()) {
                return ApiResult.fail("没有找到钱包");
            }
            //扣除手续费百分之比
            BigDecimal sxf = BigDecimalUtil.mul(byId.getNum(), new BigDecimal(ConfConstants.HANG_SALE_FEES));
            if (bean.getClassType() == 0){
                BigDecimal allPrice = BigDecimalUtil.addDouble(byId.getNum(), sxf);
                //退会收购人币
                walletInfo.setScore(BigDecimalUtil.addDouble(walletInfo.getScore(), allPrice));
                if(! userBillService.addBillRecord("退回权益卡",ConfConstants.INTEGRAL_TYPE,1,allPrice,uid,null)){
                    throw new RuntimeException("取消异常，联系客服");
                }
            }else if (bean.getClassType() == 1){
                //退回权益卡
                walletInfo.setScore(BigDecimalUtil.addDouble(walletInfo.getScore(), sxf));
                //退回佣金
                walletInfo.setMoney(BigDecimalUtil.addDouble(walletInfo.getMoney(), byId.getNum()));
                if(! userBillService.addBillRecord("退回贡献值",ConfConstants.INTEGRAL_TYPE,1,sxf,uid,null)){
                    throw new RuntimeException("取消异常，联系客服");
                }
                if(! userBillService.addBillRecord("退回贡献值",ConfConstants.COMMISSION_TYPE,1,byId.getNum(),uid,null)){
                    throw new RuntimeException("取消异常，联系客服");
                }
            }


            if (!walletService.updateById(walletInfo)) {
                return ApiResult.fail("取消异常，联系客服");
            }
        }

        if (jybBusinessOrderService.updateById(bean)){

            if (jybTradeOrderService.updateById(byId)) {

                return ApiResult.ok("取消成功");
            }else{
                throw new RuntimeException("取消异常，联系客服");
            }
        }else {
            return ApiResult.fail("取消失败");
        }


    }
    /**
     * 查询用户金币记录或佣金记录
     */
    @ApiOperation(value = "查询用户账户记录，type 0支出，1收入，category，类型")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/userBillRecord")
    public ApiResult<IPage<UserBill>>  userBillRecord(Integer type, String category, Integer page, Integer limit){
       return ApiResult.ok(userBillService.userBillRecord(LoginUtil.getUserId(),type,category,page,limit));
    }

    /**
     * 查询捐赠爱心基金
     */
    @PostMapping("/userDedicateRecord")
    public ApiResult<?>  UserDedicateRecord(){
        return ApiResult.ok(userBillService.getUserDedicateRecord());
    }



//
//    /**
//     * 删除:根据id集合
//     */
//    @ApiOperation(value = "删除:根据id集合")
//    @RequestMapping("/delete")
//    public ApiResult<String> delete(@RequestBody Integer[] ids){
//        if (jybTradeOrderService.removeByIds(Arrays.asList(ids))) {
//            return ApiResult.ok();
//        }
//        return ApiResult.fail();
//    }

    @ApiOperation(value = "查询权益卡总额")
    @RequestMapping(value = "/getZtTotal", method = RequestMethod.GET)
    public ApiResult<?> getZtTotal(){
        return ApiResult.ok(userBillService.getTzTotal());
    }

    @ApiOperation(value = "查询用户需要处理的订单")
    @RequestMapping(value = "/getUserHandleOrder", method = RequestMethod.GET)
    public ApiResult<?> getUserHandleOrder(){
        List<JybTradeOrderEntity> jybTradeOrderEntities = jybTradeOrderService.userHandleOrder();
//        if (null == jybTradeOrderEntities || jybTradeOrderEntities.isEmpty()){
//            return ApiResult.fail("")
//        }
        return ApiResult.ok(jybTradeOrderEntities);
    }





}
